
layui.define([
    'jquery',
    'flow',
    'layer'
], function (exports) {
    var $ = layui.jquery;
    var flow = layui.flow;
    var layer = layui.layer;

    // 图片懒加载
    flow.lazyimg();

    var obj = {

        /**
         * [loading 加载框]
         */
        loading : {
            show: function() {
                if( typeof(jiazaizhong) !== "undefined" ){
                    jiazaizhong = setTimeout(function(){

                        index = layer.load(1, {shade: false});
                    },1000);
                }
            },
            hide: function() {
                if( typeof(index) !== "undefined"){
                    layer.close(index);
                }
            },
            clear: function () {
                if( typeof(jiazaizhong) !== "undefined" ) {
                    // 如果一秒内数据加载出来了则清除定时器
                    window.clearTimeout(jiazaizhong);
                }

            },
            check: function () {
                if( typeof(jiazaizhong) !== "undefined" ){

                    return true;
                }else{

                    return false;
                }
            }
        },

        /**
         * [getUrl 获取一个连接的内容]
         */
        getUrl: function (url) {
            var thisObj = this;

            if( url == undefined || url.length <= 0 ){
                return false;
            }

            // 开启加载动画
            thisObj.loading.show();

            // 获取url数据
            var opt = {
                url: url,
                type: "get",
                success: function (data) {

                    // 关闭触发的动画效果
                    $('.kt-searchBg-close a').trigger('click');

                    $('.kt-body').remove();
                    $('.kt-top').after("<div class='kt-body'>"+data+"</div>");

                    // 如果两秒内数据加载出来了则清除定时器
                    thisObj.loading.clear();

                    // 关闭this.loading.
                    thisObj.loading.hide();

                },
                error: function () {

                    // 页面未正常加载设置404页面
                    $.ajax({
                        url: '/html/views/404.html',
                        type: 'get',
                        success: function (data) {

                            // 关闭触发的动画效果
                            $('.kt-searchBg-close a').trigger('click');

                            $('.kt-body').remove();
                            $('.kt-top').after("<div class='kt-body'>"+data+"</div>");

                            // 如果两秒内数据加载出来了则清除定时器
                            thisObj.loading.clear();

                            // 关闭this.loading.
                            thisObj.loading.hide();
                        },
                        error: function () {

                            // 如果两秒内数据加载出来了则清除定时器
                            thisObj.loading.clear();

                            // 关闭this.loading.
                            thisObj.loading.hide();

                            layer.msg("出错啦,抱歉!");
                        }
                    });
                }
            };

            $.ajax(opt);
        },

        /**
         * [getTpl 获取模板]
         */
        getTpl: function (url,callback) {

            var thisObj = this;

            if( url == undefined || url.length <= 0 ){
                return false;
            }

            // 开启加载动画
            thisObj.loading.show();

            // 获取url数据
            var opt = {
                url: url,
                type: "get",
                success: function (data) {

                    // 如果两秒内数据加载出来了则清除定时器
                    thisObj.loading.clear();

                    // 关闭this.loading.
                    thisObj.loading.hide();

                    callback(data);

                },
                error: function () {

                    // 页面未正常加载设置404页面
                    $.ajax({
                        url: '/html/views/404.html',
                        type: 'get',
                        success: function (data) {

                            // 如果两秒内数据加载出来了则清除定时器
                            thisObj.loading.clear();

                            // 关闭this.loading.
                            thisObj.loading.hide();

                            callback(data);
                        },
                        error: function () {

                            // 如果两秒内数据加载出来了则清除定时器
                            thisObj.loading.clear();

                            // 关闭this.loading.
                            thisObj.loading.hide();

                            layer.msg("出错啦,抱歉!");
                        }
                    });
                }
            };
            $.ajax(opt);
        },

        /**
         * [registerBox 登录框]
         */
        registerBox : {
            show :function () {
                // 获取注册模板HTMl
                obj.getTpl('/html/tpl/register.tpl', function (registerStr) {

                    layerRegister = layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        content: registerStr,
                        end:function(){
                            layer.closeAll('tips');
                        }
                    });

                });
            },
            hide: function () {
                layer.closeAll(layerRegister);
            }
        },

        /**
         * [loginBox 登录框]
         */
        loginBox: {
            show : function () {
                // 获取注册模板HTMl
                obj.getTpl('/html/tpl/login.tpl', function (loginStr) {
                    layerLogin = layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        content: loginStr,
                        end:function(){
                            layer.closeAll('tips');
                        }
                    });
                });
            },
            hide: function () {
                layer.closeAll(layerLogin);
            }
        },

        /**
         * [loginSwitch 登录注册切换]
         */
        loginSwitch: function(thisObj){

            // 关闭登录注册弹框
            layer.closeAll();

            // 获取当前展示的操作
            var type = thisObj.parents('.kt-alert-login').attr('kt-alert-type');
            if(type == 'register'){

                $('.kt-login-btn').trigger('click');
            }else{

                $('.kt-register-btn').trigger('click');
            }
        },

        /**
         * [loginSubmit 登录注册表单提交]
         */
        loginSubmit: function(thisObj){

            var isNull = true;
            var lockInput = null;
            var inputType = null;

            // 检测input框值
            thisObj.find('input').each(function(){

                // 检测是否为空
                var is = $(this).attr('kt-require');
                var val = $(this).val();

                if(is == undefined && val.length == 0 && $(this).attr('type') !== 'file'){
                    isNull = false;
                    lockInput = $(this);
                    inputType = 'border';
                    msg = '请检查此选项是否填写正确！';

                    // 设置当前input获取焦点消除tips
                    lockInput.on('focus',function(){
                        layer.close(inputTips);
                    });

                    return false;
                }

                // 检测是否存在手机号选项
                if($(this).attr('name') == 'phone' || $(this).attr('name') == 'tel'){
                    if(!checkPhone(val)){
                        isNull = false;
                        lockInput = $(this);
                        inputType = 'border';
                        msg = '手机号格式不正确，请检查！';

                        // 设置当前input获取焦点消除tips
                        lockInput.on('focus',function(){
                            layer.close(inputTips);
                        });

                        return false;
                    }
                }

            });

            // 检测textarea框值
            thisObj.find('textarea').each(function(){

                // 检测是否为空
                var is = $(this).attr('kt-require');
                var val = $(this).val();

                if(is == undefined && val.length == 0){
                    isNull = false;
                    lockInput = $(this);
                    inputType = 'border';
                    msg = '请检查此选项是否填写正确！';

                    // 设置当前input获取焦点消除tips
                    lockInput.on('focus',function(){
                        layer.close(inputTips);
                    });

                    return false;
                }

            });

            if(!isNull){

                inputTips = layer.tips(
                    msg,
                    lockInput,
                    {
                        tips: [3, '#FF5722'],
                        time: 0
                    });

                return false;
            }

            if( typeof(isSlide) == "undefined"){
                // 打开滑动验证
                slideVerify = layer.open({
                    type: 1,
                    title: '滑动完成验证',
                    area: ['310px', '248px'], //宽高
                    closeBtn: 1,
                    content: '<div class="kt-validate"><div id="captcha"></div></div>',
                    end: function(){
                        isSlide = false;
                        thisObj.find('input[name="__token__"]').remove();

                        // 如果两秒内数据加载出来了则清除定时器
                        obj.loading.clear();

                        // 关闭loading层
                        obj.loading.hide();
                    }
                });

                // 设置token
                // $.ajax({
                //     url: '/index/token/getToken.html',
                //     success: function(data){
                //         // thisObj.添加token 验证
                //         thisObj.append(data);
                //     }
                // });

                // 滑动验证初始化
                validate.init({
                    el: document.getElementById('captcha'),
                    onSuccess: function() {
                        isSlide = true;
                        thisObj.trigger('submit');
                    },
                    onFail: function(){

                    },
                    onRefresh: function(){

                    }
                });

                return false;
            }


            var opt = {
                success: function(data){
                    layer.closeAll();

                    // 设置用户信息样式
                    obj.getTpl('/html/tpl/user-top.tpl', function (html) {
                        $('.kt-user').html(html);
                    });

                    return false;

                    thisObj.find('input[name="__token__"]').remove();

                    if(data.code == 0){

                        // 设置用户信息样式
                        var html = obj.getTpl('/html/tpl/user-top.tpl');

                        // 关闭登录注册弹框
                        if( typeof(layerLogin) !== 'undefined' ){

                            layer.close(layerLogin);

                        }
                        if( typeof(layerRegister) !== 'undefined' ){

                            layer.close(layerRegister);

                        }

                        // 弹出提示
                        layer.msg(data.msg,{skin:'kt-success'});

                        $('header .nav-icons').html(html);

                    }else if(data.code == 2){

                        layer.confirm(data.msg, {
                            title: '<span class="iconfont icon-dengpao" style="font-size:20px;"></span> <span>悄悄话</span>',
                            btn: ['确认','取消'], //按钮
                            skin: 'kt-confirm'
                        }, function(){

                        });

                    }else{
                        layer.msg(data.msg,{skin:'kt-error'});
                    }
                },
                error: function(){

                    layer.close(slideVerify);

                    thisObj.find('input[name="__token__"]').remove();

                    layer.msg('哎呀，出错了！',{skin:'kt-error'});
                }
            };

            $.ajax(opt);
        },

        /**
         *	[isLogin 检测是否登录]
         */
        isLogin: function (isOpen=true) {
            // 判断第三方登录是否绑定了主体账户
            if( Cookies.get('webUserInfoOauth') && Cookies.get('webUserInfoOauth') !== 0 ){

                var msg = '<div style="display:block;text-align:center;"><span style="color:#FF5722"> * 如果您之前没有注册过kt账户，<br />则会给您重新创建一个kt账户！</span></div>';

                bindTips = layer.confirm(msg, {
                    title: '<span class="iconfont icon-dengpao" style="font-size:20px;"></span> <span>绑定提示！</span>',
                    btn: ['我已牢记'], //按钮
                    closeBtn: 0,
                    skin: 'kt-confirm'
                },function(){
                    layer.close(bindTips);

                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        shadeClose: true,
                        content: bindStr,
                        end:function(){
                            layer.closeAll('tips');
                        }
                    });

                });

                return false;

                }else if( !Cookies.get('webUserInfo') && Cookies.get('webUserInfo') !== 0 ){

                    if(isOpen){
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            shadeClose: true,
                            content: loginStr,
                            end:function(){
                                layer.closeAll('tips');
                            }
                        });
                    }
                    return false;

                }{

                return true;

            }
        },

        /**
         * 点赞动画
         */
        shape :{
            shapeObj: {
                left:           0,
                top:            0,
                style: 			{'z-index':10},
                shape:          'circle',
                fill:           'none',
                stroke:         { 'cyan' : 'cyan' },
                opacity:        { 0 : 0 },
                radius:         { 0 : 50 },
                strokeWidth:    { 50 : 0 },
                duration: 		300,
                onStart() {
                    this.el.style.display = 'block';
                },
                onComplete() {
                    this.el.style.display = 'none';
                }
            },
            replay: function (shapeObj) {

                this.objShape.tune(shapeObj).replay();
            }
        },
        burst :{
            burstObj: {
                left:           0,
                top:            0,
                style: 			{'z-index':10},
                radius:   		{ 0: 50 },
                angle:      	{ 0: 90 },
                children:{
                    radius:     { 0 : 20 }, // 小元素的大小
                    fill:       { 'cyan' : 'cyan' },
                },
                count:    		9,
                duration: 		500,
                onStart() {
                    this.el.style.display = 'block';
                },
                onComplete() {
                    this.el.style.display = 'none';
                }
            },
            replay: function (burstObj) {
                this.objBurst.tune(burstObj).replay();
            }
        },

        /**
         * [label 选择文件]
         */
        chooseFile: {
            show: function (thisObj, file) {
                imgSrc = window.URL.createObjectURL(file);

                if(imgSrc){
                    thisObj.parent('.kt-upload-btn').siblings('.kt-upload-show').fadeIn(100, function () {
                        thisObj.parent('.kt-upload-btn').siblings('.kt-upload-show').css('transform','scale(1)');
                    });

                    thisObj.parent('.kt-upload-btn').siblings('.kt-upload-show').children('.kt-headpic-show').attr('src',imgSrc);
                }
            },
            hide: function (thisObj) {

                thisObj.parent('.kt-upload-show').hide();
                thisObj.parent('.kt-upload-show').css('transform','scale(0)');

                thisObj.siblings('.kt-headpic-show').attr('src','');
            }
        },

        /**
         *  [checkIdKard 验证身份证]
         */
        checkIdKard: function (idCard) {
            var regIdNo = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
            if(!regIdNo.test(idCard)){
                layer.msg(
                    '身份证填写有误',
                    '',
                    function(){
                        $(".login_form").find('button[type="submit"]').removeAttr('disabled');
                    }
                );
                return false;
            }
            return true;
        },

        /**
         *  [checkPhone 验证手机号]
         */
        checkPhone: function (phoneNum) {
            // 验证手机号格式
            var reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
            if(!reg.test(phoneNum)){
                return false;
            }
            return true;
        }
    };

    /**
     * [ 滑动验证]
     */
    (function (window) {
        const l = 42, // 滑块边长
            r = 9, // 滑块半径
            w = 310, // canvas宽度
            h = 155, // canvas高度
            PI = Math.PI
        const L = l + r * 2 + 3 // 滑块实际边长

        function getRandomNumberByRange(start, end) {
            return Math.round(Math.random() * (end - start) + start)
        }

        function createCanvas(width, height) {
            const canvas = createElement('canvas')
            canvas.width = width
            canvas.height = height
            return canvas
        }

        function createImg(onload) {

            const img = createElement('img')
            img.crossOrigin = "Anonymous"
            img.onload = onload
            img.onerror = () => {
                // 如果两秒内数据加载出来了则清除定时器
                obj.loading.clear();

                // 关闭加载动画
                obj.loading.hide();

                img.src = getRandomImg()
            }
            img.src = getRandomImg()
            return img
        }

        function createElement(tagName) {
            return document.createElement(tagName)
        }

        function addClass(tag, className) {
            tag.classList.add(className)
        }

        function removeClass(tag, className) {
            tag.classList.remove(className)
        }

        function getRandomImg() {
            // 开启加载动画
            obj.loading.show();

            return 'https://picsum.photos/300/150/?random=' + getRandomNumberByRange(0, 1084);;
        }

        function draw(ctx, x, y, operation) {
            ctx.beginPath()
            ctx.moveTo(x, y)
            ctx.arc(x + l / 2, y - r + 2, r, 0.72*PI, 2.26 * PI)
            ctx.lineTo(x + l, y)
            ctx.arc(x + l + r - 2, y + l / 2, r, 1.21*PI, 2.78 * PI)
            ctx.lineTo(x + l, y + l)
            ctx.lineTo(x, y + l)
            ctx.arc(x + r - 2, y + l / 2, r + 0.4, 2.76 * PI, 1.24 * PI, true)
            ctx.lineTo(x, y)
            ctx.lineWidth = 2
            ctx.fillStyle = 'rgba(255, 255, 255, 0.7)'
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)'
            ctx.stroke()
            ctx[operation]()
            ctx.globalCompositeOperation = 'overlay'
        }

        function sum(x, y) {
            return x + y
        }

        function square(x) {
            return x * x
        }

        class validate {
            constructor({el, onSuccess, onFail, onRefresh}) {
                el.style.position = el.style.position || 'relative'
                this.el = el
                this.onSuccess = onSuccess
                this.onFail = onFail
                this.onRefresh = onRefresh
            }

            init() {
                this.initDOM()
                this.initImg()
                this.bindEvents()
            }

            initDOM() {
                const canvas = createCanvas(w, h) // 画布
                const block = canvas.cloneNode(true) // 滑块
                const sliderContainer = createElement('div')
                const refreshIcon = createElement('div')
                const sliderMask = createElement('div')
                const slider = createElement('div')
                const sliderIcon = createElement('span')
                const text = createElement('span')

                block.className = 'block'
                sliderContainer.className = 'sliderContainer'
                refreshIcon.className = 'refreshIcon'
                sliderMask.className = 'sliderMask'
                slider.className = 'slider'
                sliderIcon.className = 'iconfont icon-jiantouarrow484'
                text.innerHTML = '向右滑动填充拼图完成验证'
                text.className = 'sliderText'

                const el = this.el
                el.appendChild(canvas)
                el.appendChild(refreshIcon)
                el.appendChild(block)
                slider.appendChild(sliderIcon)
                sliderMask.appendChild(slider)
                sliderContainer.appendChild(sliderMask)
                sliderContainer.appendChild(text)
                el.appendChild(sliderContainer)

                Object.assign(this, {
                    canvas,
                    block,
                    sliderContainer,
                    refreshIcon,
                    slider,
                    sliderMask,
                    sliderIcon,
                    text,
                    canvasCtx: canvas.getContext('2d'),
                    blockCtx: block.getContext('2d')
                })
            }

            initImg() {
                const img = createImg(() => {
                    this.draw()
                    this.canvasCtx.drawImage(img, 0, 0, w, h)
                    this.blockCtx.drawImage(img, 0, 0, w, h)
                    const y = this.y - r * 2 - 1
                    const ImageData = this.blockCtx.getImageData(this.x - 3, y, L, L)
                    this.block.width = L
                    this.blockCtx.putImageData(ImageData, 0, y)

                    // 如果两秒内数据加载出来了则清除定时器
                    obj.loading.clear();

                    // 关闭加载动画
                    obj.loading.hide();
                })

                this.img = img
            }

            draw() {
                // 随机创建滑块的位置
                this.x = getRandomNumberByRange(L + 10, w - (L + 10))
                this.y = getRandomNumberByRange(10 + r * 2, h - (L + 10))
                draw(this.canvasCtx, this.x, this.y, 'fill')
                draw(this.blockCtx, this.x, this.y, 'clip')
            }

            clean() {
                this.canvasCtx.clearRect(0, 0, w, h)
                this.blockCtx.clearRect(0, 0, w, h)
                this.block.width = w
            }

            bindEvents() {
                this.el.onselectstart = () => false
                this.refreshIcon.onclick = () => {

                    // 判断图片（canvas）是否正在加载
                    if($('.layui-icon-loading').length > 0){
                        return false;
                    }

                    $('#captcha .slider').find('.iconfont').removeClass('icon-close1');
                    $('#captcha .slider').find('.iconfont').removeClass('icon-duigou');
                    $('#captcha .slider').find('.iconfont').addClass('icon-jiantou');
                    this.reset()
                    typeof this.onRefresh === 'function' && this.onRefresh()
                }

                // 判断操作系统
                var sUserAgent = navigator.userAgent.toLowerCase();
                var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
                var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
                var bIsMidp = sUserAgent.match(/midp/i) == "midp";
                var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
                var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
                var bIsAndroid = sUserAgent.match(/android/i) == "android";
                var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
                var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";

                if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){

                    var evenStart = 'mousedown';
                    var evenMove = 'mousemove';
                    var evenEnd = 'mouseup';
                }else{

                    var evenStart = 'touchstart';
                    var evenMove = 'touchmove';
                    var evenEnd = 'touchend';
                }

                let originX, originY, trail = [], isMouseDown = false
                this.slider.addEventListener(evenStart, function (e) {

                    // 判断图片（canvas）是否正在加载
                    if($('.layui-icon-loading').length > 0){
                        return false;
                    }

                    if(e.type == 'touchstart'){
                        var typeX = e.touches[0].pageX;
                        var typeY = e.touches[0].pageY;
                    }else{
                        var typeX = e.x;
                        var typeY = e.y;
                    }

                    originX = typeX, originY = typeY

                    isMouseDown = true
                })
                document.addEventListener(evenMove, (e) => {

                    if (!isMouseDown) return false

                    if(e.type == 'touchmove'){
                        var typeX = e.touches[0].pageX;
                        var typeY = e.touches[0].pageY;
                    }else{
                        var typeX = e.x;
                        var typeY = e.y;
                    }

                    const moveX = typeX - originX
                    const moveY = typeY - originY

                    if (moveX < 0 || moveX + 38 >= w) return false
                    this.slider.style.left = moveX + 'px'
                    var blockLeft = (w - 40 - 20) / (w - 40) * moveX
                    this.block.style.left = blockLeft + 'px'

                    addClass(this.sliderContainer, 'sliderContainer_active')
                    this.sliderMask.style.width = moveX + 'px'
                    trail.push(moveY)
                })

                document.addEventListener(evenEnd, (e) => {
                    if (!isMouseDown) return false

                    if(e.type == 'touchend'){
                        var typeX = e.changedTouches[0].pageX;
                        var typeY = e.changedTouches[0].pageY;
                    }else{
                        var typeX = e.x;
                        var typeY = e.y;
                    }

                    isMouseDown = false
                    if (typeX == originX) return false
                    removeClass(this.sliderContainer, 'sliderContainer_active')
                    this.trail = trail
                    const {spliced, verified} = this.verify()
                    if (spliced) {
                        if (verified) {
                            addClass(this.sliderContainer, 'sliderContainer_success')

                            $('#captcha .slider').find('.iconfont').removeClass('icon-jiantou');
                            $('#captcha .slider').find('.iconfont').removeClass('icon-close1');
                            $('#captcha .slider').find('.iconfont').addClass('icon-duigou');

                            typeof this.onSuccess === 'function' && this.onSuccess()
                        } else {
                            addClass(this.sliderContainer, 'sliderContainer_fail')

                            $('#captcha .slider').find('.iconfont').removeClass('icon-close1');
                            $('#captcha .slider').find('.iconfont').removeClass('icon-duigou');
                            $('#captcha .slider').find('.iconfont').addClass('icon-jiantou');

                            this.text.innerHTML = '再试一次'
                            this.reset()
                        }
                    } else {
                        addClass(this.sliderContainer, 'sliderContainer_fail')

                        $('#captcha .slider').find('.iconfont').removeClass('icon-jiantou');
                        $('#captcha .slider').find('.iconfont').removeClass('icon-duigou');
                        $('#captcha .slider').find('.iconfont').addClass('icon-close1');

                        typeof this.onFail === 'function' && this.onFail()
                        setTimeout(() => {
                            $('#captcha .slider').find('.iconfont').removeClass('icon-close1');
                            $('#captcha .slider').find('.iconfont').removeClass('icon-duigou');
                            $('#captcha .slider').find('.iconfont').addClass('icon-jiantou');
                            this.reset()
                        }, 1000)
                    }
                })
            }

            verify() {
                const arr = this.trail // 拖动时y轴的移动距离
                const average = arr.reduce(sum) / arr.length
                const deviations = arr.map(x => x - average)
                const stddev = Math.sqrt(deviations.map(square).reduce(sum) / arr.length)
                const left = parseInt(this.block.style.left)
                return {
                    spliced: Math.abs(left - this.x) < 10,
                    verified: stddev !== 0 , // 简单验证下拖动轨迹，为零时表示Y轴上下没有波动，可能非人为操作
                }
            }

            reset() {

                // 如果两秒内数据加载出来了则清除定时器
                obj.loading.clear();
                // 关闭loading层
                obj.loading.hide();

                this.sliderContainer.className = 'sliderContainer'
                this.slider.style.left = 0
                this.block.style.left = 0
                this.sliderMask.style.width = 0
                this.clean()
                this.img.src = getRandomImg()
            }

        }

        window.validate = {
            init: function (opts) {
                return new validate(opts).init()
            }
        }
    }(window))

    //输出test接口
    exports('fun', obj);
});